package com.ars.main;

import com.ars.db.DBTools;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import javax.swing.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginController {
    @FXML
    private TextField tfWebsiteName;
    @FXML
    private PasswordField tfPassword;

    @FXML
    public void loginButtonAction() {
        User.setName(tfWebsiteName.getText().trim());
        User.setPassword(tfPassword.getText().trim());
        String WebsiteName1 = null;
        String Password1 = null;
        if (!User.getName().equals("") && !User.getPassword().equals("")) {
            try {
                ResultSet rs = new DBTools().query("select * from website");
                while (rs.next()) {
                    if (User.getName().equals(rs.getString("name")) && User.getPassword().equals(rs.getString("password"))) {
                        WebsiteName1 = rs.getString("name");
                        Password1 = rs.getString("password");
                        User.setLimit(rs.getInt("limit"));
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (User.getName().equals(WebsiteName1) && User.getPassword().equals(Password1)) {
                Stage stage = new Stage();
                if (User.getLimit() == 1) {
                    //1.超级管理员界面
                    stage.setScene(new Scene(loadPane("../main/MainPane.fxml")));
                } else if (User.getLimit() == 2) {
                    //2.管理员界面
                    stage.setScene(new Scene(loadPane("../main/MainPane.fxml")));
                } else {
                    //3.网点界面
                    stage.setScene(new Scene(loadPane("../website/WebsiteMainPane.fxml")));
                }
                stage.setTitle("航空订票管理系统");
                stage.show();
                //登录舞台关闭
                StageCollection.getInstance().get("loginStage").close();
                //将主舞台添加到舞台收集器
                StageCollection.getInstance().put("mainStage", stage);
            } else {
                JOptionPane.showMessageDialog(null, "帐号或密码不正确,请重新输入!");
            }

        } else {
            JOptionPane.showMessageDialog(null, "不能为空,请输入!");
        }
    }

    @FXML
    public void cancelButtonAction() {
        StageCollection.getInstance().get("loginStage").close();
    }


    private Parent loadPane(String paneName) {
        Parent root = null;
        try {
            root = FXMLLoader.load(getClass().getResource(paneName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return root;
    }
}
